package com.suning.sawp.web.controller;

import java.security.Principal;
import java.util.Date;
import java.util.List;

import javax.validation.Valid;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.suning.sawp.constants.ConfigConstants;
import com.suning.sawp.constants.ErrorCodeConstants;
import com.suning.sawp.constants.LoggerConstants;
import com.suning.sawp.dto.common.ReturnMsg;
import com.suning.sawp.dto.mainpush.StoreManDto;
import com.suning.sawp.dto.yxwt.BatchUpdateRevisitInfo;
import com.suning.sawp.dto.yxwt.CateInfo;
import com.suning.sawp.dto.yxwt.CateInfoDto;
import com.suning.sawp.dto.yxwt.LogisticsReq;
import com.suning.sawp.dto.yxwt.OrderStaffInfo;
import com.suning.sawp.dto.yxwt.RevisitInfo;
import com.suning.sawp.dto.yxwt.SaledNoPickDto;
import com.suning.sawp.dto.yxwt.SaledNoTakeDto;
import com.suning.sawp.intf.logistics.LogisticsService;
import com.suning.sawp.intf.storeman.StoreManService;
import com.suning.sawp.intf.yxwt.SaledNoTakeService;
import com.suning.sawp.po.yxwt.SaledNoTake;
import com.suning.sawp.service.util.DateUtils;
import com.suning.sawp.vo.logistics.LogisticsVo;
import com.suning.sawp.web.exception.MobileException;
import com.suning.sawp.web.exception.MyGsonView;

/**
 * 
 * 订单查询controller<br>
 * 〈功能详细描述〉
 * 
 * @author Wuxiao
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Controller
@RequestMapping("/yxwt")
public class SaledNoTakeController extends DjBaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoggerConstants.SAWP_SERVICE);

    @Autowired
    SaledNoTakeService saledNoTakeService;

    @Autowired
    StoreManService storeManService;

    @Autowired
    LogisticsService logisticsService;

    /**
     * 
     * 功能描述: 查询订单列表<br>
     * 〈功能详细描述〉
     *
     * @param storeCode 门店代码
     * @param telNo 手机号
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param start 起始值
     * @param limit 每页大小
     * @param principal
     * @return
     * @throws MobileException
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryOrderList.do")
    public MyGsonView queryOrderList(int index, int size, String accessStatus, String cateCode, Principal principal)
            throws MobileException {
        ReturnMsg<SaledNoTakeDto> returnMsg = new ReturnMsg<SaledNoTakeDto>();
        Object[] args = { principal.getName(), index, size, accessStatus, cateCode };
        LOGGER.info("queryOrderList staffId:{}, index:{}, size:{}, accessStatus:{}, cateCode:{}", args);
        StoreManDto storeManDto = storeManService.queryStoreManAttachInfo(principal.getName());
        // 校验店员信息
        if (storeManDto == null) {
            LOGGER.error("queryOrderList storeManDto is null for " + principal.getName());
            returnMsg.setErrorCode(ErrorCodeConstants.ERR_0027);
            returnMsg.setRetFlag(ReturnMsg.FAIL);
            returnMsg.setErrorMessage(ErrorCodeConstants.ERR_MAP.get(ErrorCodeConstants.ERR_0027));
            return setGsonView(returnMsg);
        }

        // 校验请求入参
        if (StringUtils.isBlank(storeManDto.getStoreCode()) || StringUtils.isBlank(principal.getName()) || index < 0
                || size <= 0 || size > ConfigConstants.PAGE_SIZE_LIMIT) {
            LOGGER.error("queryOrderList  input error for staffid  " + principal.getName());
            returnMsg.setErrorCode(ErrorCodeConstants.ERR_0001);
            returnMsg.setRetFlag(ReturnMsg.FAIL);
            returnMsg.setErrorMessage(ErrorCodeConstants.ERR_MAP.get(ErrorCodeConstants.ERR_0001));
            return setGsonView(returnMsg);
        }

        ReturnMsg<List<SaledNoTake>> result = saledNoTakeService.queryOrderList(index, size, cateCode,
                storeManDto.getStoreCode(), principal.getName(), accessStatus);

        SaledNoTakeDto data = new SaledNoTakeDto();
        if (result != null && ReturnMsg.SUCCESS.equals(result.getRetFlag())) {
            data.setOrderList(result.getData());
            data.setLimitTime(
                    DateUtils.getDateStrByFormat(DateUtils.getNextDay(new Date(), -1), DateUtils.DEFAULT_DATE_PATTERN));
            returnMsg.setData(data);
        } else {
            LOGGER.error("queryOrderList  input result fail  for staffid  " + principal.getName());
            returnMsg.setErrorCode(ErrorCodeConstants.ERR_0028);
            returnMsg.setRetFlag(ReturnMsg.FAIL);
            returnMsg.setErrorMessage(ErrorCodeConstants.ERR_MAP.get(ErrorCodeConstants.ERR_0028));
        }
        return setGsonView(returnMsg);
    }

    /**
     * 查询已销未提订单列表信息_新
     *
     * @param index modify by chenhui 2017年5月16日09:40:39 index原为分页起始页，现作为页码使用，从第一页开始
     * @param size
     * @param accessStatus
     * @param cateCode
     * @param principal
     * @return
     * @throws MobileException
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryOrderListByStatus.do")
    public MyGsonView queryOrderListByStatus(int index, int size, String accessStatus, Principal principal)
            throws MobileException {
        ReturnMsg<SaledNoPickDto> returnMsg = new ReturnMsg<SaledNoPickDto>();
        Object[] args = { principal.getName(), index, size, accessStatus };
        LOGGER.info("queryOrderListByStatus staffId:{}, index:{}, size:{}, accessStatus:{}, cateCode:{}", args);
        StoreManDto storeManDto = storeManService.queryStoreManAttachInfo(principal.getName());
        // 校验店员信息
        if (storeManDto == null) {
            LOGGER.error("queryOrderListByStatus storeManDto is null for " + principal.getName());
            returnMsg.setErrorCode(ErrorCodeConstants.ERR_0027);
            returnMsg.setRetFlag(ReturnMsg.FAIL);
            returnMsg.setErrorMessage(ErrorCodeConstants.ERR_MAP.get(ErrorCodeConstants.ERR_0027));
            return setGsonView(returnMsg);
        }

        // 校验请求入参
        if (StringUtils.isBlank(accessStatus) || StringUtils.isBlank(storeManDto.getStoreCode())
                || StringUtils.isBlank(principal.getName()) || index <= 0 || size <= 0
                || size > ConfigConstants.PAGE_SIZE_LIMIT) {
            LOGGER.error("queryOrderListByStatus  input error for staffid  " + principal.getName());
            returnMsg.setErrorCode(ErrorCodeConstants.ERR_0001);
            returnMsg.setRetFlag(ReturnMsg.FAIL);
            returnMsg.setErrorMessage(ErrorCodeConstants.ERR_MAP.get(ErrorCodeConstants.ERR_0001));
            return setGsonView(returnMsg);
        }

        int startRow = (index - 1) * size;
        ReturnMsg<SaledNoPickDto> result = saledNoTakeService.queryOrderListByStatus(startRow, size, "", "",
                principal.getName(), accessStatus);

        if (result != null && ReturnMsg.SUCCESS.equals(result.getRetFlag())) {
            LOGGER.info("queryOrderListByStatus result :", result.getData());
            returnMsg.setData(result.getData());
        } else {
            LOGGER.error("queryOrderListByStatus  input result fail  for staffid  " + principal.getName());
            returnMsg.setErrorCode(ErrorCodeConstants.ERR_0028);
            returnMsg.setRetFlag(ReturnMsg.FAIL);
            returnMsg.setErrorMessage(ErrorCodeConstants.ERR_MAP.get(ErrorCodeConstants.ERR_0028));

        }
        return setGsonView(returnMsg);
    }

    /**
     * 
     * 功能描述: 已销未提列表信息，by 人员工号和品类<br>
     * 
     * @param index modify by chenhui 2017年5月16日09:40:39 index原为分页起始页，现作为页码使用，从第一页开始
     * @param size
     * @param staffId
     * @param cateCode
     * @param principal
     * @return
     * @throws MobileException
     */
    @RequestMapping("/queryOrderListByCate.do")
    public MyGsonView queryOrderListByCate(int index, int size, String staffId, String cateCode, Principal principal)
            throws MobileException {
        ReturnMsg<SaledNoPickDto> returnMsg = new ReturnMsg<SaledNoPickDto>();
        Object[] args = { principal.getName(), index, size, staffId, cateCode };
        LOGGER.info("queryOrderListByStatus staffId:{}, index:{}, size:{}, accessStatus:{}, cateCode:{}", args);
        StoreManDto storeManDto = storeManService.queryStoreManAttachInfo(principal.getName());
        // 校验店员信息
        if (storeManDto == null) {
            LOGGER.error("queryOrderListByStatus storeManDto is null for " + principal.getName());
            returnMsg.setErrorCode(ErrorCodeConstants.ERR_0027);
            returnMsg.setRetFlag(ReturnMsg.FAIL);
            returnMsg.setErrorMessage(ErrorCodeConstants.ERR_MAP.get(ErrorCodeConstants.ERR_0027));
            return setGsonView(returnMsg);
        }

        // 校验请求入参
        if (StringUtils.isBlank(staffId) || StringUtils.isBlank(storeManDto.getStoreCode())
                || StringUtils.isBlank(principal.getName()) || index <= 0 || size <= 0
                || size > ConfigConstants.PAGE_SIZE_LIMIT) {
            LOGGER.error("queryOrderListByStatus  input error for staffid  " + principal.getName());
            returnMsg.setErrorCode(ErrorCodeConstants.ERR_0001);
            returnMsg.setRetFlag(ReturnMsg.FAIL);
            returnMsg.setErrorMessage(ErrorCodeConstants.ERR_MAP.get(ErrorCodeConstants.ERR_0001));
            return setGsonView(returnMsg);
        }

        int startRow = (index - 1) * size;
        ReturnMsg<SaledNoPickDto> result = saledNoTakeService.queryOrderListByStatus(startRow, size, cateCode,
                storeManDto.getStoreCode(), staffId, SaledNoTake.AccConstants.TOTAL);

        if (result != null && ReturnMsg.SUCCESS.equals(result.getRetFlag())) {
            LOGGER.info("queryOrderListByStatus result :", result.getData());
            returnMsg.setData(result.getData());
        } else {
            LOGGER.error("queryOrderListByStatus  input result fail  for staffid  " + principal.getName());
            returnMsg.setErrorCode(ErrorCodeConstants.ERR_0028);
            returnMsg.setRetFlag(ReturnMsg.FAIL);
            returnMsg.setErrorMessage(ErrorCodeConstants.ERR_MAP.get(ErrorCodeConstants.ERR_0028));

        }
        return setGsonView(returnMsg);
    }

    /**
     * 查询已销未提统计信息
     *
     * @param cateCode
     * @param principal
     * @return
     * @throws MobileException
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryCateInfo.do")
    public MyGsonView queryCateInfo(String categoryCode, Principal principal) throws MobileException {
        ReturnMsg<CateInfoDto> returnMsg = new ReturnMsg<CateInfoDto>();
        LOGGER.info("queryCateInfo staffId:{}", principal.getName());
        StoreManDto storeManDto = storeManService.queryStoreManAttachInfo(principal.getName());
        // 校验店员信息
        if (storeManDto == null) {
            LOGGER.error("queryCateInfo storeManDto is null for " + principal.getName());
            returnMsg.setErrorCode(ErrorCodeConstants.ERR_0027);
            returnMsg.setRetFlag(ReturnMsg.FAIL);
            returnMsg.setErrorMessage(ErrorCodeConstants.ERR_MAP.get(ErrorCodeConstants.ERR_0027));
            return setGsonView(returnMsg);
        }

        // 校验请求入参
        if (CollectionUtils.isEmpty(storeManDto.getCategories()) || StringUtils.isBlank(principal.getName())) {
            LOGGER.error("queryCateInfo  input error for staffid  " + principal.getName());
            returnMsg.setErrorCode(ErrorCodeConstants.ERR_0001);
            returnMsg.setRetFlag(ReturnMsg.FAIL);
            returnMsg.setErrorMessage(ErrorCodeConstants.ERR_MAP.get(ErrorCodeConstants.ERR_0001));
            return setGsonView(returnMsg);
        }

        CateInfoDto cateInfoDto = new CateInfoDto();

        ReturnMsg<List<CateInfo>> result = saledNoTakeService.queryCateInfoByCateCodeList(storeManDto, categoryCode);

        if (result != null && ReturnMsg.SUCCESS.equals(result.getRetFlag())) {
            cateInfoDto.setCateInfoList(result.getData());
            cateInfoDto.setLimitTime(
                    DateUtils.getDateStrByFormat(DateUtils.getNextDay(new Date(), -1), DateUtils.DEFAULT_DATE_PATTERN));
            returnMsg.setData(cateInfoDto);
        } else {
            LOGGER.error("queryCateInfo  input result fail  for staffid  " + principal.getName());
            returnMsg.setErrorCode(ErrorCodeConstants.ERR_0028);
            returnMsg.setRetFlag(ReturnMsg.FAIL);
            returnMsg.setErrorMessage(ErrorCodeConstants.ERR_MAP.get(ErrorCodeConstants.ERR_0028));

        }
        return setGsonView(returnMsg);
    }

    /**
     * 更新回访信息
     *
     * @param orderItemId
     * @param reVisitContent
     * @param reVisitStatus
     * @param principal
     * @return
     * @throws MobileException
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/updateRevisit.do")
    public MyGsonView updateRevisit(String orderItemId, String reVisitContent, String reVisitStatus,
            Principal principal) throws MobileException {
        ReturnMsg<String> returnMsg = new ReturnMsg<String>();
        Object[] args = { principal.getName(), orderItemId, reVisitContent, reVisitStatus };
        LOGGER.info("queryOrderList orderItemId:{}, reVisitContent:{}, reVisitStatus:{}", args);

        // 校验请求入参
        if (StringUtils.isBlank(orderItemId) || StringUtils.isBlank(reVisitStatus)) {
            LOGGER.error("queryOrderList  input error for staffid  " + principal.getName());
            returnMsg.setErrorCode(ErrorCodeConstants.ERR_0001);
            returnMsg.setRetFlag(ReturnMsg.FAIL);
            returnMsg.setErrorMessage(ErrorCodeConstants.ERR_MAP.get(ErrorCodeConstants.ERR_0001));
            return setGsonView(returnMsg);
        }

        returnMsg = saledNoTakeService.updateRevisit(orderItemId, reVisitContent, reVisitStatus);
        return setGsonView(returnMsg);
    }

    /**
     * 批量更新已销未提回访备注
     *
     * @param batchUpdateRevisitInfo
     * @param principal
     * @return
     * @throws MobileException
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/batchUpdateRevisit.do")
    public MyGsonView batchUpdateRevisit(@RequestBody BatchUpdateRevisitInfo batchUpdateRevisitInfo,
            Principal principal) throws MobileException {
        ReturnMsg<String> returnMsg = new ReturnMsg<String>();
        Object[] args = { principal.getName(), batchUpdateRevisitInfo };
        LOGGER.info("batchUpdateRevisit orderItemId:{}, reVisitContent:{}, reVisitStatus:{}", args);
        StoreManDto storeManDto = storeManService.queryStoreManAttachInfo(principal.getName());
        // 校验店员信息
        if (storeManDto == null) {
            LOGGER.error("batchUpdateRevisit storeManDto is null for " + principal.getName());
            returnMsg.setErrorCode(ErrorCodeConstants.ERR_0027);
            returnMsg.setRetFlag(ReturnMsg.FAIL);
            returnMsg.setErrorMessage(ErrorCodeConstants.ERR_MAP.get(ErrorCodeConstants.ERR_0027));
            return setGsonView(returnMsg);
        }
        List<RevisitInfo> reList = batchUpdateRevisitInfo.getMyOrderList();

        if (CollectionUtils.isNotEmpty(reList)) {
            for (RevisitInfo item : reList) {
                if (StringUtils.isBlank(item.getOrderItemId()) || StringUtils.isBlank(item.getReVisitStatus())) {
                    throw new MobileException(ErrorCodeConstants.ERR_0001);
                }
            }
        }

        returnMsg = saledNoTakeService.batchUpdateRevisit(batchUpdateRevisitInfo, storeManDto);
        return setGsonView(returnMsg);
    }

    /**
     * 查询物流信息 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param logisticsRequest
     * @param bindResult
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryLogisticsForYxwt.do")
    @ResponseBody
    public ReturnMsg<LogisticsVo> queryLogistics(@Valid LogisticsReq logisticsRequest, BindingResult bindResult) {
        LOGGER.debug("queryLogistics IN,logisticsRequest={}", logisticsRequest.toString());
        ReturnMsg<LogisticsVo> result = new ReturnMsg<LogisticsVo>();
        result.setRetFlag(ReturnMsg.FAIL);
        if (bindResult.hasErrors()) {
            result.setError(bindResult.getFieldError().getCode(), bindResult.getFieldError().getDefaultMessage());
            return result;
        }
        try {
            LogisticsVo logisticsVo = logisticsService.queryLogisticsForYxwt(logisticsRequest);
            result.setData(logisticsVo);
            result.setRetFlag(ReturnMsg.SUCCESS);
        } catch (Exception e) {
            LOGGER.error("新物流数据查询失败", e);
            result.setErrorMessage("物流数据查询失败！");
        }
        return result;
    }

    /**
     * 查询对应品类下各店员的销售数量
     *
     * @param cateCode
     * @param principal
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryOrderCountByCata.do")
    public MyGsonView queryOrderCountByCata(String cateCode, Principal principal) {
        ReturnMsg<List<OrderStaffInfo>> returnMsg = new ReturnMsg<List<OrderStaffInfo>>();
        Object[] args = { principal.getName(), cateCode };
        LOGGER.info("queryOrderCountByCata staffid:{}, catacode:{}", args);
        // 校验请求入参
        if (StringUtils.isBlank(cateCode)) {
            LOGGER.error("queryOrderList  input error for staffid  " + principal.getName());
            returnMsg.setErrorCode(ErrorCodeConstants.ERR_0001);
            returnMsg.setRetFlag(ReturnMsg.FAIL);
            returnMsg.setErrorMessage(ErrorCodeConstants.ERR_MAP.get(ErrorCodeConstants.ERR_0001));
            return setGsonView(returnMsg);
        }

        StoreManDto storeManDto = storeManService.queryStoreManAttachInfo(principal.getName());
        // 校验店员信息
        if (storeManDto == null) {
            LOGGER.error("queryCateInfo storeManDto is null for " + principal.getName());
            returnMsg.setErrorCode(ErrorCodeConstants.ERR_0027);
            returnMsg.setRetFlag(ReturnMsg.FAIL);
            returnMsg.setErrorMessage(ErrorCodeConstants.ERR_MAP.get(ErrorCodeConstants.ERR_0027));
            return setGsonView(returnMsg);
        }
        returnMsg = saledNoTakeService.queryOrderCountByCata(cateCode, storeManDto);

        return setGsonView(returnMsg);
    }

}
